from langchain.tools import tool
from pydantic import BaseModel, Field
from typing import List
import httpx
from parsel import Selector
from markdownify import markdownify
import re


class Location(BaseModel):
    id: str = Field(description="城市的ID")
    name: str = Field(description="城市名")
    path: str = Field(description="城市的层级，如‘中国， 湖北， 咸宁’")


class Now(BaseModel):
    precipitation: float = Field(description="单位时间降雨量，单位是mm")
    temperature: float = Field(description="实时温度，单位是摄氏度")
    pressure: float = Field(description="气压，单位是hPa")
    humidity: float = Field(description="湿度")
    windDirection: str = Field(description="风向")
    windDirectionDegree: float = Field(description="风向度")
    windSpeed: float = Field(description="风速，单位 m/s")
    windScale: str = Field(description="风的等级，如微风、大风")
    feelst: float = Field(description="体感温度")


class Alarm(BaseModel):
    id: str = Field(description="警报编号")
    title: str = Field("警报信息的标题")
    signaltype: str = Field("警报信息的类别")
    signallevel: str = Field("警报的级别：如黄色")
    effective: str = Field("警报开始时间")
    eventType: str = Field("警报类型的编码")
    severity: str = Field("警报的严重成都，如‘YELLOW’")
    type: str = Field("类型")


class ServerResponse(BaseModel):
    location: Location = Field(description="城市地点信息的结构化字段")
    now: Now = Field(description="实时天气的结构数据")
    alarm: List[Alarm]
    jieQi: str = Field(description="当天是什么节气")
    lastUpdate: str = Field(description="最近更新时间")


# @tool
# async def get_real_time_weather(city_code: str) -> ServerResponse:
#     """调用API的方式从中国气象网获取城市的当前天气，需要用city_code当作参数。
#     如果只需要获取当前的天气（如温度、湿度等），这个tool比 名为fetch的tool更快，应该优先选择
#     """
#     url = "https://weather.cma.cn/api/now/%s" % city_code
#     headers = {
#         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
#     }
#     async with httpx.AsyncClient() as client:
#         resp = await client.get(url, headers=headers)
#         resp.raise_for_status()
#         data = resp.json()["data"]
#         ret = ServerResponse(**data)
#         return ret

@tool
async def get_weather_from_web(city_code: str) -> str:
    """通过访问URL链接
    """
    url = "https://weather.cma.cn/web/weather/%s.html"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    }
    async with httpx.AsyncClient() as client:
        resp = await client.get(url%city_code, headers=headers)
        resp.encoding = "utf-8"
        selector = Selector(text=resp.text, encoding="utf-8")
        result = markdownify(html=selector.css(".hp").get(), strip=["img"])
        return result
    

if __name__ == '__main__':
    import asyncio
    result = asyncio.run(get_weather_from_web.ainvoke("57590"))
    print(result)

